﻿// Copyright (c) MichaConrad. All rights reserved. See License.txt in the project root for license information.

namespace LinqToLdapExtensions.Scope
{
    using System;
    using System.Collections.Generic;
    using LinqToLdap;

    /// <summary>
    /// Provides a thread safe implementation to have <see cref="IDirectoryContextFactory.GetCurrentContext()"/>
    /// for each thread using the [<see cref="ThreadStaticAttribute"/>].
    /// Supports multiple instances of <see cref="IDirectoryContextFactory"/> in one thread.
    /// </summary>
    public class ThreadStaticDirectoryContext : CurrentDirectoryContext
    {
        /// <summary>
        /// The store.
        /// </summary>
        [ThreadStatic]
        private static IDictionary<IDirectoryContextFactory, IDirectoryContext> store;

        /// <summary>
        /// Initializes a new instance of the <see cref="ThreadStaticDirectoryContext"/> class.
        /// </summary>
        /// <param name="directoryContextFactory">
        /// The directory context factory.
        /// </param>
        public ThreadStaticDirectoryContext(IDirectoryContextFactory directoryContextFactory)
            : base(directoryContextFactory)
        {
        }

        /// <summary>
        /// Gets the store.
        /// </summary>
        protected override IDictionary<IDirectoryContextFactory, IDirectoryContext> Store
        {
            get
            {
                if (store == null)
                {
                    store = new Dictionary<IDirectoryContextFactory, IDirectoryContext>();
                }

                return store;
            }
        }
    }
}
